import tkinter as tk
from tkinter import filedialog, messagebox
from ddddocr import DdddOcr
import logging

# 设置基本的日志配置
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

# 初始化OCR对象
ocr = DdddOcr()

file_path = None


def select_image():
    global file_path
    try:
        # 打开文件选择对话框
        file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg *.jpeg *.png *.bmp *.gif")])
        if file_path:
            result_text.config(state=tk.NORMAL)
            result_text.delete(1.0, tk.END)
            result_text.insert(tk.END, "图片已选择，请点击'一键识别'")
            result_text.config(state=tk.DISABLED)
        else:
            result_text.config(state=tk.NORMAL)
            result_text.delete(1.0, tk.END)
            result_text.insert(tk.END, "未选择图片")
            result_text.config(state=tk.DISABLED)
    except Exception as e:
        logging.error(f"select_image error: {e}")
        messagebox.showerror("Error", f"An error occurred while selecting an image: {e}")


def recognize_image():
    global file_path
    try:
        if not file_path:
            messagebox.showwarning("警告", "请先选择一张图片")
            return

        with open(file_path, 'rb') as f:
            img_bytes = f.read()
        result = ocr.classification(img_bytes)
        # 将识别结果转换为大写
        result_upper = result.upper()

        result_text.config(state=tk.NORMAL)
        result_text.delete(1.0, tk.END)
        result_text.insert(tk.END, f"识别结果: {result_upper}")
        result_text.config(state=tk.DISABLED)
    except Exception as e:
        logging.error(f"recognize_image error: {e}")
        messagebox.showerror("Error", f"An error occurred during image recognition: {e}")


def center_window(window):
    try:
        window.update_idletasks()
        width = window.winfo_width()
        height = window.winfo_height()
        x_offset = (window.winfo_screenwidth() - width) // 2
        y_offset = (window.winfo_screenheight() - height) // 2
        window.geometry(f'+{x_offset}+{y_offset}')
    except Exception as e:
        logging.error(f"center_window error: {e}")
        messagebox.showerror("Error", f"An error occurred while centering the window: {e}")


if __name__ == "__main__":
    try:
        # 创建主窗口
        root = tk.Tk()
        root.title("图片验证码识别")
        root.geometry("400x200")

        # 确保窗口居中
        center_window(root)

        # 创建一个框架用于布局
        frame = tk.Frame(root)
        frame.pack(expand=True)

        # 创建按钮，用于选择图片
        select_button = tk.Button(frame, text="选择图片", command=select_image)
        select_button.pack(pady=10)

        # 创建按钮，用于触发识别
        recognize_button = tk.Button(frame, text="一键识别", command=recognize_image)
        recognize_button.pack(pady=10)

        # 创建Text小部件，用于显示识别结果，并允许复制
        result_text = tk.Text(frame, wrap=tk.WORD, height=5, state=tk.DISABLED)
        result_text.pack(pady=10)

        # 运行主循环
        root.mainloop()
    except Exception as e:
        logging.error(f"Main program error: {e}")
        messagebox.showerror("Error", f"An unexpected error occurred: {e}")


